package com.bjyhl.ui.recycler;

import com.chad.library.adapter.base.entity.MultiItemEntity;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;

public class MultipleItemBean implements MultiItemEntity {

    private final ReferenceQueue<LinkedHashMap<Object, Object>> ITEM_QUEUE = new ReferenceQueue<>();
    private final LinkedHashMap<Object, Object> MULTIPLE_FIELDS = new LinkedHashMap<>();
    private final SoftReference<LinkedHashMap<Object, Object>> FIELD_REFERENCE
            = new SoftReference<>(MULTIPLE_FIELDS, ITEM_QUEUE);

    @Override
    public int getItemType() {
        return (int)FIELD_REFERENCE.get().get(MultipleFields.ITEM_TYPE);
    }

    public final <T> T getField(Object key) {
        return (T) FIELD_REFERENCE.get().get(key);
    }

    public final LinkedHashMap<?, ?> getFields() {
        return FIELD_REFERENCE.get();
    }

    public final MultipleItemBean setField(Object key, Object value) {
        FIELD_REFERENCE.get().put(key, value);
        return this;
    }

    MultipleItemBean(LinkedHashMap<Object, Object> fields){
        FIELD_REFERENCE.get().putAll(fields);

    }

    static class MultipleItemBeanBuilder {
        private static final LinkedHashMap<Object, Object> FIELDS = new LinkedHashMap<>();

        public MultipleItemBeanBuilder(){
            FIELDS.clear();
        }

        public MultipleItemBeanBuilder setItem(int itemType) {
            FIELDS.put(MultipleFields.ITEM_TYPE, itemType);
            return this;
        }

        public MultipleItemBeanBuilder setField(Object key, Object value) {
            FIELDS.put(key, value);
            return this;
        }

        public MultipleItemBeanBuilder setFields(LinkedHashMap<?, ?> map) {
            FIELDS.putAll(map);
            return this;
        }

        public final MultipleItemBean build() {
            return new MultipleItemBean(FIELDS);
        }
    }
}
